<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 组织架构头部布局 -->
        <tree-tools :tree-node="company" is-root @addDepts="addDepts" />
        <!-- 树形控件渲染 -->
        <el-tree :data="departs" :props="defaultProps" default-expand-all>
          <!-- data：表示当前节点的数据 -->
          <tree-tools
            slot-scope="{ data }"
            :tree-node="data"
            @delDepts="getDepartment"
            @addDepts="addDepts"
            @editDepts="editDepts"
          />
        </el-tree>
      </el-card>
    </div>
    <!-- 弹框 -->
    <add-depts
      ref="addDepts"
      :visible.sync="dialogVisible"
      :tree-node="node"
      @addDepts="getDepartment"
    />
  </div>
</template>

<script>
import treeTools from './components/tree-tools.vue'
import { getDepartmentList } from '@/api/departments'
import { tranListToTreeData } from '@/utils'
import addDepts from './components/add-depts.vue'
export default {
  components: {
    treeTools,
    addDepts
  },
  data() {
    return {
      company: {}, // 公司信息
      departs: [], // 部门数据
      // 注意：树形控件，默认读取label属性作为节点名称，读取children属性来渲染子节点
      // 可以通过props属性来修改节点名称和渲染子节点的属性读取
      defaultProps: {
        label: 'name'
      },
      dialogVisible: false, // 控制弹框打开关闭
      node: {}, // 保存当前节点信息
      loading: true
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 编辑部门
    editDepts(treeNode) {
      this.dialogVisible = true
      this.node = treeNode
      // 调用弹框组件实例中的获取部门详情方法
      this.$refs.addDepts.getDepartmentDetail(treeNode.id)
    },
    // 新增部门
    addDepts(treeNode) {
      this.dialogVisible = true
      this.node = treeNode
    },
    // 获取部门列表数据
    async getDepartment() {
      this.loading = true
      const { depts, companyName } = await getDepartmentList()
      this.departs = tranListToTreeData(depts, '')
      this.company = { name: companyName, manager: '负责人', id: '' }
      this.loading = false
    }
  }
}
</script>

<style>
.tree-card {
  padding: 30px  140px;
  font-size:14px;
}
</style>
